package com.ldkj.panzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ldkj.panzh.param.BarrierGateParam;
import com.ldkj.panzh.param.MonitoringPointParam;
import com.ldkj.panzh.param.MonitoringPointDeviceParam;
import com.ldkj.panzh.service.BarrierGateService;
import com.ldkj.panzh.utils.CommentUtils;
import com.ldkj.panzh.vo.BarrierGateVO;
import com.ldkj.panzh.vo.MonitoringPointVO;
import com.ldkj.panzh.vo.MonitoringPointDeviceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 道闸（园区卡口）功能 实现类
 *
 * @author qiancheng
 * @date 2025-11-19
 */
@Slf4j
@Service
public class BarrierGateServiceImpl implements BarrierGateService {

    // API网关相关常量
    private static final String ARTEMIS_PATH = "/artemis";
    // 园区卡口查询接口
    private static final String GET_MONITORING_POINT_API = ARTEMIS_PATH + "/api/resource/v1/monitoringPoint/search";
    // 园区卡口设备查询接口
    private static final String GET_MONITORING_POINT_DEVICE_API = ARTEMIS_PATH + "/api/resource/v1/monitoringPointDevice/search";
    // 停车场设备在线状态查询接口
//    private static final String GET_PMS_DEVICE_STATUS_API = ARTEMIS_PATH + "/api/nms/v1/online/pms/device/get";
    private static final String GET_PMS_DEVICE_STATUS_API = ARTEMIS_PATH + "/api/nms/v1/online/pms/device/get";
//    private static final String GET_PMS_DEVICE_STATUS_API =  "/api/nms/v1/online/pms/device/get";
    // 停车场网管资源类型默认值
    private static final String DEFAULT_RESOURCE_TYPE = "cross";

    // 接口参数常量
    private static final String PAGE_NO = "pageNo";
    private static final String PAGE_SIZE = "pageSize";
    private static final String SUCCESS_CODE = "0";

    @Autowired
    public CommentUtils commentUtils;

    /**
     * 查询道闸列表
     * 使用停车场设备在线状态接口 /api/nms/v1/online/pms/device/get
     *
     * @param barrierGateParam 查询参数
     * @return 道闸列表数据
     */
    @Override
    public List<BarrierGateVO> queryBarrierGates(BarrierGateParam barrierGateParam) throws Exception {

        //设置平台参数（优先使用参数中的值，否则使用配置文件默认值）
        ArtemisConfig config = commentUtils.createArtemisConfig(
                barrierGateParam.getAppKey(),
                barrierGateParam.getAppSecret(),
                barrierGateParam.getHost());

        // 准备基础参数
        Map<String, Object> paramMap = new HashMap<>(8);
        // resourceType为必填参数，优先使用传入值，否则使用默认值
        String resourceType = barrierGateParam.getResourceType() != null ? 
                barrierGateParam.getResourceType() : DEFAULT_RESOURCE_TYPE;
        paramMap.put("resourceType", resourceType);
        paramMap.put(PAGE_NO, barrierGateParam.getPageNo());
        paramMap.put(PAGE_SIZE, barrierGateParam.getPageSize());

        // 添加可选参数
        // regionId: 区域id（优先使用regionId，其次使用regionIndexCodes的第一个）
        if (barrierGateParam.getRegionId() != null && !barrierGateParam.getRegionId().isEmpty()) {
            paramMap.put("regionId", barrierGateParam.getRegionId());
        } else if (barrierGateParam.getRegionIndexCodes() != null && !barrierGateParam.getRegionIndexCodes().isEmpty()) {
            paramMap.put("regionId", barrierGateParam.getRegionIndexCodes().get(0));
        }
        // includeSubNode: 是否包含下级区域（"1"包含，"0"不包含）
        if (barrierGateParam.getIncludeSubNode() != null && !barrierGateParam.getIncludeSubNode().isEmpty()) {
            paramMap.put("includeSubNode", barrierGateParam.getIncludeSubNode());
        } else if (barrierGateParam.getIsSubRegion() != null) {
            paramMap.put("includeSubNode", barrierGateParam.getIsSubRegion() ? "1" : "0");
        }
        // status: 状态筛选（"1"-在线，"0"-离线，"-1"-未检测）
        if (barrierGateParam.getStatus() != null && !barrierGateParam.getStatus().isEmpty()) {
            paramMap.put("status", barrierGateParam.getStatus());
        }
        // indexCodes: 设备标识集合
        if (barrierGateParam.getIndexCodes() != null && !barrierGateParam.getIndexCodes().isEmpty()) {
            paramMap.put("indexCodes", barrierGateParam.getIndexCodes());
        }

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_PMS_DEVICE_STATUS_API);
        List<BarrierGateVO> resultList = new ArrayList<>();

        try {
            String body = JSON.toJSONString(paramMap);
            log.info("查询停车场设备在线状态请求参数: {}", body);
            
            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");
            log.info("查询停车场设备在线状态响应: {}", response);
            
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String list = data.getString("list");
                    if (list != null && !list.isEmpty()) {
                        // 手动解析并映射字段
                        List<JSONObject> dataList = JSON.parseArray(list, JSONObject.class);
                        for (JSONObject item : dataList) {
                            BarrierGateVO vo = new BarrierGateVO();
                            vo.setIndexCode(item.getString("indexCode"));
                            vo.setName(item.getString("cn")); // cn: 设备名称
                            vo.setRegionIndexCode(item.getString("regionIndexCode"));
                            vo.setRegionName(item.getString("regionName"));
                            vo.setTreatyType(item.getString("treatyType"));
                            // online: 在线状态（0-离线，1-在线）
                            vo.setStatus(item.getInteger("online"));
                            // 该接口不返回道闸开关状态，设置默认值
                            vo.setGateStatus(0);
                            resultList.add(vo);
                        }
                    }
                }
            } else {
                String errorMsg = String.format("接口返回错误: %s，响应内容: %s",
                        jsonObject.getString("msg"), response);
                log.error(errorMsg);
                throw new Exception(errorMsg);
            }
        } catch (Exception e) {
            String errorMsg = "查询停车场设备在线状态失败";
            log.error(errorMsg, e);
            throw new Exception(errorMsg, e);
        }
        return resultList;
    }

    /**
     * 查询道闸数量和状态统计
     *
     * @param barrierGateParam 查询参数
     * @return 统计数据（总数、在线数、离线数、异常数等）
     */
    @Override
    public Map<String, Object> queryBarrierGateStats(BarrierGateParam barrierGateParam) throws Exception {
        // 查询所有道闸数据
        List<BarrierGateVO> allGates = queryBarrierGates(barrierGateParam);

        // 统计数据
        Map<String, Object> stats = new HashMap<>(8);
        int totalCount = allGates.size();
        int onlineCount = 0;
        int offlineCount = 0;
        int openCount = 0;
        int closeCount = 0;
        int abnormalCount = 0;

        for (BarrierGateVO gate : allGates) {
            // 统计设备在线状态
            if (gate.getStatus() != null) {
                if (gate.getStatus() == 1) {
                    onlineCount++;
                } else {
                    offlineCount++;
                }
            }

            // 统计道闸开关状态
            if (gate.getGateStatus() != null) {
                switch (gate.getGateStatus()) {
                    case 0:
                        closeCount++;
                        break;
                    case 1:
                        openCount++;
                        break;
                    case 2:
                        abnormalCount++;
                        break;
                    default:
                        break;
                }
            }
        }

        stats.put("totalCount", totalCount);
        stats.put("onlineCount", onlineCount);
        stats.put("offlineCount", offlineCount);
        stats.put("openCount", openCount);
        stats.put("closeCount", closeCount);
        stats.put("abnormalCount", abnormalCount);
        stats.put("onlineRate", totalCount > 0 ? String.format("%.2f%%", (onlineCount * 100.0 / totalCount)) : "0.00%");

        return stats;
    }

    /**
     * 查询园区卡口（监控点）列表
     *
     * @param monitoringPointParam 查询参数
     * @return 园区卡口列表数据
     */
    @Override
    public List<MonitoringPointVO> searchMonitoringPoints(MonitoringPointParam monitoringPointParam) throws Exception {
        //设置平台参数（优先使用参数中的值，否则使用配置文件默认值）
        ArtemisConfig config = commentUtils.createArtemisConfig(
                monitoringPointParam.getAppKey(),
                monitoringPointParam.getAppSecret(),
                monitoringPointParam.getHost());

        // 准备基础参数
        Map<String, Object> paramMap = new HashMap<>(8);
        paramMap.put(PAGE_NO, monitoringPointParam.getPageNo());
        paramMap.put(PAGE_SIZE, monitoringPointParam.getPageSize());

        // 添加可选参数
        if (monitoringPointParam.getName() != null && !monitoringPointParam.getName().isEmpty()) {
            paramMap.put("name", monitoringPointParam.getName());
        }
        if (monitoringPointParam.getRegionIndexCodes() != null && !monitoringPointParam.getRegionIndexCodes().isEmpty()) {
            paramMap.put("regionIndexCodes", monitoringPointParam.getRegionIndexCodes());
        }
        if (monitoringPointParam.getIsSubRegion() != null) {
            paramMap.put("isSubRegion", monitoringPointParam.getIsSubRegion());
        }
        if (monitoringPointParam.getCapabilitySet() != null && !monitoringPointParam.getCapabilitySet().isEmpty()) {
            paramMap.put("capabilitySet", monitoringPointParam.getCapabilitySet());
        }
        if (monitoringPointParam.getOrderBy() != null && !monitoringPointParam.getOrderBy().isEmpty()) {
            paramMap.put("orderBy", monitoringPointParam.getOrderBy());
        }
        if (monitoringPointParam.getOrderType() != null && !monitoringPointParam.getOrderType().isEmpty()) {
            paramMap.put("orderType", monitoringPointParam.getOrderType());
        }

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_MONITORING_POINT_API);
        List<MonitoringPointVO> resultList = new ArrayList<>();

        try {
            String body = JSON.toJSONString(paramMap);
            log.info("查询园区卡口列表请求参数: {}", body);
            
            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");
            log.info("查询园区卡口列表响应: {}", response);
            
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String list = data.getString("list");
                    if (list != null && !list.isEmpty()) {
                        resultList = JSON.parseArray(list, MonitoringPointVO.class);
                    }
                }
            } else {
                String errorMsg = String.format("接口返回错误: %s，响应内容: %s",
                        jsonObject.getString("msg"), response);
                log.error(errorMsg);
                throw new Exception(errorMsg);
            }
        } catch (Exception e) {
            String errorMsg = "查询园区卡口列表失败";
            log.error(errorMsg, e);
            throw new Exception(errorMsg, e);
        }
        return resultList;
    }

    /**
     * 查询园区卡口设备列表
     *
     * @param monitoringPointDeviceParam 查询参数
     * @return 园区卡口设备列表数据
     */
    @Override
    public List<MonitoringPointDeviceVO> searchMonitoringPointDevices(MonitoringPointDeviceParam monitoringPointDeviceParam) throws Exception {
        //设置平台参数（优先使用参数中的值，否则使用配置文件默认值）
        ArtemisConfig config = commentUtils.createArtemisConfig(
                monitoringPointDeviceParam.getAppKey(),
                monitoringPointDeviceParam.getAppSecret(),
                monitoringPointDeviceParam.getHost());

        // 准备基础参数
        Map<String, Object> paramMap = new HashMap<>(8);
        paramMap.put(PAGE_NO, monitoringPointDeviceParam.getPageNo());
        paramMap.put(PAGE_SIZE, monitoringPointDeviceParam.getPageSize());

        // 添加可选参数
        if (monitoringPointDeviceParam.getName() != null && !monitoringPointDeviceParam.getName().isEmpty()) {
            paramMap.put("name", monitoringPointDeviceParam.getName());
        }
        if (monitoringPointDeviceParam.getRegionIndexCodes() != null && !monitoringPointDeviceParam.getRegionIndexCodes().isEmpty()) {
            paramMap.put("regionIndexCodes", monitoringPointDeviceParam.getRegionIndexCodes());
        }
        if (monitoringPointDeviceParam.getIsSubRegion() != null) {
            paramMap.put("isSubRegion", monitoringPointDeviceParam.getIsSubRegion());
        }
        if (monitoringPointDeviceParam.getCapabilitySet() != null && !monitoringPointDeviceParam.getCapabilitySet().isEmpty()) {
            paramMap.put("capabilitySet", monitoringPointDeviceParam.getCapabilitySet());
        }
        if (monitoringPointDeviceParam.getOrderBy() != null && !monitoringPointDeviceParam.getOrderBy().isEmpty()) {
            paramMap.put("orderBy", monitoringPointDeviceParam.getOrderBy());
        }
        if (monitoringPointDeviceParam.getOrderType() != null && !monitoringPointDeviceParam.getOrderType().isEmpty()) {
            paramMap.put("orderType", monitoringPointDeviceParam.getOrderType());
        }

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_MONITORING_POINT_DEVICE_API);
        List<MonitoringPointDeviceVO> resultList = new ArrayList<>();

        try {
            String body = JSON.toJSONString(paramMap);
            log.info("查询园区卡口设备列表请求参数: {}", body);
            
            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");
            log.info("查询园区卡口设备列表响应: {}", response);
            
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String list = data.getString("list");
                    if (list != null && !list.isEmpty()) {
                        resultList = JSON.parseArray(list, MonitoringPointDeviceVO.class);
                    }
                }
            } else {
                String errorMsg = String.format("接口返回错误: %s，响应内容: %s",
                        jsonObject.getString("msg"), response);
                log.error(errorMsg);
                throw new Exception(errorMsg);
            }
        } catch (Exception e) {
            String errorMsg = "查询园区卡口设备列表失败";
            log.error(errorMsg, e);
            throw new Exception(errorMsg, e);
        }
        return resultList;
    }
}
